<!DOCTYPE html>
<html lang=zh-CN>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:description" content="samuel-24276的博客">
    <meta property="og:type" content="website">
    <meta name="description" content="samuel-24276的博客">
    <meta name="keyword"  content="aircloud">
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
        You&#39;re doing it wrong - samuel-24276的博客 | samuel-24276&#39;s Blog
        
    </title>

    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/myblog/css/aircloud.css">

    
<link rel="stylesheet" href="/myblog/css/gitment.css">

    <!--<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">-->
    <link href="//at.alicdn.com/t/font_620856_28hi1hpxx24.css" rel="stylesheet" type="text/css">
    <!-- ga & ba script hoook -->
    <script></script>
<meta name="generator" content="Hexo 7.1.1"></head>

<body>

<div class="site-nav-toggle" id="site-nav-toggle">
    <button>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
    </button>
</div>

<div class="index-about">
    <i> Like what you do, do what you like </i>
</div>

<div class="index-container">
    
    <div class="index-left">
        
<div class="nav" id="nav">
    <div class="avatar-name">
        <div class="avatar ">
            <img src="/myblog/img/avatar.jpg" />
        </div>
        <div class="name">
            <i>samuel-24276</i>
        </div>
    </div>
    <div class="contents" id="nav-content">
        <ul>
            <li >
                <a href="/myblog/">
                    <i class="iconfont icon-shouye1"></i>
                    <span>主页</span>
                </a>
            </li>
            <li >
                <a href="/myblog/tags">
                    <i class="iconfont icon-biaoqian1"></i>
                    <span>标签</span>
                </a>
            </li>
            <li >
                <a href="/myblog/archives">
                    <i class="iconfont icon-guidang2"></i>
                    <span>存档</span>
                </a>
            </li>
            <li >
                <a href="/myblog/collect/">
                    <i class="iconfont icon-shoucang1"></i>
                    <span>收藏</span>
                </a>
            </li>
            <li >
                <a href="/myblog/about/">
                    <i class="iconfont icon-guanyu2"></i>
                    <span>关于</span>
                </a>
            </li>
            
            <li>
                <a id="search">
                    <i class="iconfont icon-sousuo1"></i>
                    <span>搜索</span>
                </a>
            </li>
            
        </ul>
    </div>
    
        <div id="toc" class="toc-article">
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Rules-of-thumbs"><span class="toc-text">Rules of thumbs</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#What-about-using-QtConcurrent-instead"><span class="toc-text">What about using QtConcurrent instead?</span></a></li></ol>
</div>
    
</div>


<div class="search-field" id="search-field">
    <div class="search-bg" id="search-bg"></div>
    <div class="search-container">
        <div class="search-input">
            <span id="esc-search"> <i class="icon-fanhui iconfont"></i></span>
            <input id="search-input"/>
            <span id="begin-search">搜索</span>
        </div>
        <div class="search-result-container" id="search-result-container">

        </div>
    </div>
</div>

        <div class="index-about-mobile">
            <i> Like what you do, do what you like </i>
        </div>
    </div>
    
    <div class="index-middle">
        <!-- Main Content -->
        


<div class="post-container">
    <div class="post-title">
        You're doing it wrong
    </div>

    <div class="post-meta">
        <span class="attr">发布于：<span>2022-05-18 15:24:21</span></span>
        
        <span class="attr">标签：/
        
        <a class="tag" href="/myblog/tags/#Qt" title="Qt">Qt</a>
        <span>/</span>
        
        <a class="tag" href="/myblog/tags/#文章翻译" title="文章翻译">文章翻译</a>
        <span>/</span>
        
        <a class="tag" href="/myblog/tags/#线程" title="线程">线程</a>
        <span>/</span>
        
        
        </span>
        <span class="attr">访问：<span id="busuanzi_value_page_pv"></span>
</span>
</span>
    </div>
    <div class="post-content no-indent">
        <p>这篇文章是关于QThread的使用。这是我当时的同事布拉德三年前在博客上发表的一篇文章的答案:</p>
<p><a target="_blank" rel="noopener" href="https://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/">You’re doing it wrong</a></p>
<p>在他的博客文章中，Brad解释说，他看到许多用户通过子类化QThread来滥用它，给这个子类添加了一些槽，并在构造函数中做了这样的事情:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">moveToThread</span>(<span class="keyword">this</span>);</span><br></pre></td></tr></table></figure>

<p>它们将线程移动到自身。正如Brad提到的，这是错误的:QThread应该是管理线程的接口。因此，它应该从创建线程中使用。</p>
<p><strong>QThread对象中的slot不会在该线程中运行，在QThread的子类中拥有slot是一种糟糕的做法</strong>。</p>
<p>但是Brad继续反对对QThread进行任何子类化。他声称这违背了适当的面向对象设计。这是我不同意的地方。在run()中放入代码是扩展QThread的一种有效的面向对象的方式:QThread表示刚开始一个事件循环的线程，子类表示扩展来执行run()中内容的线程。</p>
<p>在Brad发表了这篇文章之后，一些社区成员开始了反对将QThread子类化的运动。问题是有许多完全有效的理由来子类化QThread。</p>
<p>在Qt 5.0和Qt 4.8.4中，QThread的文档进行了更改，因此示例代码不涉及子类。它有许多行在一个线程里运行若干代码的锅炉板。甚至还有一个漏洞:QThread永远不会退出和被销毁。</p>
<p>我在IRC上被一个用户问了一个问题，他为了在线程中运行一些简单的代码而遵循了这个例子。他费了好大劲才弄明白如何正确地销毁这个线程。这就是我写这篇博客的动机。</p>
<p>如果你允许子类化QThread，这是你得到的:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">WorkerThread</span> : <span class="keyword">public</span> QThread &#123;</span><br><span class="line">    <span class="function"><span class="type">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">MyObject::startWorkInAThread</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    WorkerThread *workerThread = <span class="keyword">new</span> WorkerThread;</span><br><span class="line">    <span class="built_in">connect</span>(workerThread, <span class="built_in">SIGNAL</span>(<span class="built_in">finished</span>()),</span><br><span class="line">            workerThread, <span class="built_in">SLOT</span>(<span class="built_in">deleteLater</span>()));</span><br><span class="line">    workerThread-&gt;<span class="built_in">start</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这段代码不再泄漏，并且更加简单，开销更少，因为它不会创建无用的对象。</p>
<p>The Qt threading example <a target="_blank" rel="noopener" href="https://code.woboq.org/qt5/qtbase/examples/network/threadedfortuneserver/fortunethread.cpp.html#_ZN13FortuneThread3runEv">threadedfortuneserver</a> is an example that uses this pattern to run blocking operations and is much simpler than the equivalent using a worker object.</p>
<p>I have submitted a <a target="_blank" rel="noopener" href="https://codereview.qt-project.org/45271">patch to the documentation</a> to not discourage sub-classing QThread anymore.</p>
<h1 id="Rules-of-thumbs"><a href="#Rules-of-thumbs" class="headerlink" title="Rules of thumbs"></a>Rules of thumbs</h1><p><strong>When to subclass and when not to?</strong></p>
<ul>
<li>如果你真的不需要在线程中使用事件循环，你应该子类化。&#x20;</li>
<li>如果你需要一个事件循环和处理信号和线程中的槽，你可能不需要子类化。</li>
</ul>
<h1 id="What-about-using-QtConcurrent-instead"><a href="#What-about-using-QtConcurrent-instead" class="headerlink" title="What about using QtConcurrent instead?"></a>What about using QtConcurrent instead?</h1><p>QThread是一个相当低的级别，你应该更好地使用一个更高级别的API，如QtConcurrent。</p>
<p>现在，<strong>QtConcurrent有它自己的一些问题</strong>:它被绑定到一个线程池，所以如果你想运行阻塞操作，它不是一个好的解决方案。它在实现中也存在一些问题，会带来一些性能开销。所有这些都是可以解决的。甚至Qt 5.1也可能会有一些改进。</p>
<p><strong>另一个不错的选择是c++ 11标准库中的std::thread和std::async</strong>，它们现在是在线程中运行代码的标准方式。好消息是它仍然可以很好地与Qt一起工作:所有其他Qt线程原语都可以与本机线程一起使用。(如果需要，Qt会自动创建一个QThread)。</p>
<hr>

        
            <div class="donate-container">
    <div class="donate-button">
        <button id="donate-button">赞赏</button>
    </div>
    <div class="donate-img-container hide" id="donate-img-container">
        <img id="donate-img" src="" data-src="/myblog/img/donate.jpg">
        <p> 感谢鼓励 </p>
    </div>
</div>
        
        <br />
        <div id="comment-container">
        </div>
        <div id="disqus_thread"></div>
        <div id="lv-container"></div>
        <div class="giscus"></div>
    </div>
</div>

    </div>
</div>


<footer class="footer">
    <ul class="list-inline text-center">
        
        

        

        

        
        <li>
            <a target="_blank"  href="https://github.com/samuel-24276">
                            <span class="fa-stack fa-lg">
                                <i class="iconfont icon-github"></i>
                            </span>
            </a>
        </li>
        

        

    </ul>
    
    <p>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://github.com/samuel-24276">samuel-24276&#39;s Page</a></span>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/">北京-未备案</a></span>
        <span>/</span>
        
        <span><a href="#">返回顶部</a></span>
        <span>/</span>
        
    </p>
    
    <p>
        <span id="busuanzi_container_site_pv">
            <span id="busuanzi_value_site_pv"></span>PV
        </span>
        <span id="busuanzi_container_site_uv">
            <span id="busuanzi_value_site_uv"></span>UV
        </span>
        Created By <a target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a>  Theme <a target="_blank" rel="noopener" href="https://github.com/aircloud/hexo-theme-aircloud">AirCloud</a></p>
</footer>




</body>

<script>
    // We expose some of the variables needed by the front end
    window.hexo_search_path = "search.json"
    window.hexo_root = "/myblog/"
    window.isPost = true
</script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<script src="/myblog/js/index.js"></script>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






    <script type="text/javascript">
       (function() {
           if (typeof LivereTower === 'function') { return; }

           var j, d = document.getElementById('lv-container');

           d.setAttribute('data-id','city');
           d.setAttribute('data-uid' , 'MTAyMC80OTA5OC8yNTU5Mw==');

           j = document.createElement('script');
           j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
           j.async = true;

           d.appendChild(j);
       })();
    </script>
    <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

</html>
